package com.qc.dao.impl;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import com.qc.dao.FootprintDao;
import com.qc.entity.FootprintEntity;

@SuppressWarnings({ "unchecked", "rawtypes" })
@Repository("footprintDao")
public class FootprintDaoImpl implements FootprintDao{

	@Resource(name="jdbcTemplate")
	private JdbcTemplate jdbcTemplate;
	
	@Override
	public int saveFootprint(FootprintEntity footprintEntity) {
		String sql = "insert into t_footprint(ss_id,user_id)values(?,?)";
		
		return jdbcTemplate.update(sql,new Object[]{footprintEntity.getSsId(),footprintEntity.getUserId()});
	}

	@Override
	public FootprintEntity getFootprintById(long ssId, long userId) {
		
		String sql = "select * from t_footprint where ss_id = "+ssId+" and user_id = "+userId;
		FootprintEntity footprintEntity = new FootprintEntity();
		try {
			footprintEntity = (FootprintEntity) jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper(FootprintEntity.class));
		} catch (DataAccessException e) {
		}
		return footprintEntity;
	}

	@Override
	public int updateFootprint(long bId) {
		String sql = "update t_footprint set modified_time = CURRENT_TIMESTAMP where b_id = "+bId;
		
		return jdbcTemplate.update(sql);
	}

	@Override
	public List<FootprintEntity> listAlFootprint(long ssId, long userId, int pageNo,int pageSize) {
		
		int beginRow = (pageNo - 1)* pageSize;
		
		String sql = "select b.*,a.* "
				+ " from t_footprint a"
				+ " left join t_user b on b.user_id = a.user_id "
				+ " where 1 = 1";
		
			if (ssId != 0) {
				sql += " and a.ss_id ="+ssId+" ";
			}
			
			if (userId != 0) {
				sql += " and a.user_id ="+userId+" ";
			}
		
			sql += " order by a.modified_time DESC ";
			sql += " LIMIT "+ String.valueOf(beginRow)+ "," + pageSize;
			
			return jdbcTemplate.query(sql, new BeanPropertyRowMapper(FootprintEntity.class));
	}

}
